package com.example.communist_app_api.common.security;

import com.example.communist_app_api.db.pojoDto.Permission;
import com.example.communist_app_api.db.pojoDto.Role;
import com.example.communist_app_api.db.pojoDto.User;
import com.example.communist_app_api.exception.UserCountLockException;
import com.example.communist_app_api.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author love~mlm
 * @version 1.0
 * Create by 2022/11/19 12:57
 */
@Component
public class    CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private ModuleService moduleService;
    @Autowired
    private ActionService actionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取用户user
        User user = userService.getUserInfo(username);
        //判断用户状态
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }else if ("1".equals(user.getStatus())){
            throw new UserCountLockException("该用户账号已被封禁，具体联系管理员！");
        }
        //根据用户id查询该用户有角色的集合
        ArrayList<Integer> roleIdList = userRoleService.getRoleIdByUserId(user.getId());
        //根据角色id查询角色实体对象
        Collection<Role> roles  = roleService.getRoleByRoleId(roleIdList);

        //roles.add(role);

        // List<GrantedAuthority> authorities = new ArrayList<>();

        // authorities.add(new SimpleGrantedAuthority("ROLE_"+role));

        boolean statusFlag;
        if (user.getStatus() == 0) {
             statusFlag = true;
        }else {
             statusFlag = false;
        }

        return new org.springframework.security.core.userdetails.User(
                user.getName(),
                bCryptPasswordEncoder.encode(user.getPassword()),
                true,
                true,
                true,
                true,
                //给用户赋权，调用getAuthorities方法，传入Collection<Role> roles
                getAuthorities(roles)
        );
    }
    // UTIL
    private final Collection<? extends GrantedAuthority> getAuthorities(final Collection<Role> roles) {
        return getGrantedAuthorities(getPrivileges(roles));
    }

    private final List<String> getPrivileges(final Collection<Role> roles) {
        //返回权限module_code+action_code,已经知道了role对象
        final List<String> privileges = new ArrayList<>();

        ArrayList<Integer> permissionIdList= new ArrayList<>();
        for (final Role role : roles) {

            permissionIdList = rolePermissionService.getPermissionIdByRoleId(role.getId());
        }
        for (final Integer permissionId : permissionIdList) {
             Permission permission = permissionService.getPermissionByPermissionId(permissionId);
               if(!(permission.getActionId()==0||permission.getModuleId() ==0)){
                   String actionCode = actionService.getActionCodeByActionId(permission.getActionId());
                   String  moduleCode = moduleService.getModuleCodeByModuleId(permission.getModuleId());
                   String privilege = moduleCode.concat("_").concat(actionCode);
                   //添加权限到privileges的List中，TODO权限不重复还没有实现
                   privileges.add(privilege);
               }
        }
        return privileges;
    }

    private final List<GrantedAuthority> getGrantedAuthorities(final List<String> privileges) {
        final List<GrantedAuthority> authorities = new ArrayList<>();
        for (final String privilege : privileges) {
            authorities.add(new SimpleGrantedAuthority(privilege));
        }
        return authorities;
    }
}
